<!--
 * @Author: your name
 * @Date: 2021-07-20 10:33:35
 * @LastEditTime: 2021-09-16 17:58:22
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \usp-osm-frondend\src\views\couponsCenter\couponMgmt\index.vue
-->
<template>
  <div
    class="source"
    v-loading="pageLoading"
    :element-loading-text="loadingText"
  >
    <div class="content">
      <v-notes>
        <div class="filterStyle">
          <el-form
            label-width="120px"
            :model="searchList"
            ref="searchForm"
            class="search-form"
            size="small"
          >
            <el-row class="search-row">
              <el-col :span="24">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="券池编号">
                      <el-input
                        placeholder="券池编号"
                        v-model="searchList.couponCode"
                        @input="searchList.couponCode=searchList.couponCode.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
                        clearable
                        v-on:keyup.enter.native="fetchList()"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="券池名称">
                      <el-input
                        placeholder="券池名称"
                        v-model="searchList.couponName"
                        @input="searchList.couponName=searchList.couponName.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
                        clearable
                        v-on:keyup.enter.native="fetchList()"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="券池来源">
                        <el-select
                        v-model="searchList.source"
                        placeholder="券池来源"
                        style="width: 95%"
                        >
                          <el-option key label="全部" value></el-option>
                          <el-option
                              v-for="item in lookupItems.SOURCEOFCOUPONPOOL"
                              :key="item.id"
                              :label="item.dicName"
                              :value="item.dicCode"
                          ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                </el-row>
                <el-collapse-transition>
                  <div class="filterContent" v-if="showContent">
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <el-form-item label="业务类型">
                          <el-select
                          v-model="searchList.businessType"
                          placeholder="业务类型"
                          style="width: 95%"
                          >
                            <el-option key label="全部" value></el-option>
                            <el-option
                                v-for="item in lookupItems.BUSINESSTYPE"
                                :key="item.id"
                                :label="item.dicName"
                                :value="item.dicCode"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="状态">
                          <el-select
                          v-model="searchList.status"
                          placeholder="状态"
                          style="width: 95%"
                          >
                            <el-option key label="全部" value></el-option>
                            <el-option
                                v-for="item in lookupItems.COUPONPOOLSTATUS"
                                :key="item.id"
                                :label="item.dicName"
                                :value="item.dicCode"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="冻结状态">
                          <el-select
                          v-model="searchList.frozenState"
                          placeholder="冻结状态"
                          style="width: 95%"
                          >
                            <el-option key label="全部" value></el-option>
                            <el-option
                                v-for="item in lookupItems.FROZENSTATE"
                                :key="item.id"
                                :label="item.dicName"
                                :value="item.dicCode"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <el-form-item label="服务商">
                          <el-input
                            placeholder="服务商"
                            v-model="searchList.serviceProvidersName"
                            @input="searchList.serviceProvidersName=searchList.serviceProvidersName.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
                            clearable
                            v-on:keyup.enter.native="fetchList()"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="创建时间">
                          <div class="block">
                            <el-date-picker
                              v-model="searchList.createTime"
                              type="daterange"
                              range-separator="至"
                              :picker-options="pickerOptions"
                              :default-value="[new Date(), new Date()]"
                              value-format="yyyy-MM-dd"
                              start-placeholder="开始时间"
                              end-placeholder="结束时间"
                            ></el-date-picker>
                          </div>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </el-collapse-transition>
              </el-col>
            </el-row>
            <el-row class="search-row">
              <el-col :span="12" :offset="12" style="text-align: right">
                <el-button
                  @click="closeFilter"
                  :icon="
                    showContent ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
                  "
                  class="white-btn filterClose"
                  >{{ showContent ? '折叠' : '展开' }}</el-button
                >
                <el-button
                  @click="resetForm"
                  icon="el-icon-refresh-left"
                  class="white-btn">
                  重置
                </el-button>
                <el-button
                  @click="fetchList(true)"
                  icon="el-icon-search"
                  class="dark-btn search-btn">
                  搜索
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </v-notes>
      <div class="mb-lg">
        <v-table
          :data="tableData"
          ref="table"
          :listLoading="listLoading"
          :loadingText="loadingText"
          :paginationTotal="total"
          v-on:pageSizeChange="pageSizeChange"
          v-on:currentPageChange="currentPageChange"
          v-on:handleSelectionChange="handleSelectionChange"
          border
          pagination
        >
          <div slot="header">
            <el-button
              class="search-btn"
              @click="addCoupon"
              v-if="$auth('ticketCenter:ticketPoolManagement:add')"
            >新建</el-button>
            <el-button
              @click="takeEffect"
              :disabled="isTake"
              class="search-btn"
              v-if="$auth('ticketCenter:ticketPoolManagement:effect')"
            >生效</el-button>
          </div>
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            label="券池编号"
            prop="couponCode"
            align="center"
            min-width="120"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span class="colorLink" @click="toDetail(scope.row)">
                  {{ scope.row.couponCode }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="券池名称"
            prop="couponName"
            align="center"
            min-width="150"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="券池来源"
            align="center"
            prop="source"
            min-width="110"
            :show-overflow-tooltip="true"
          >
          <template slot-scope="scope">
            {{ getDictionaryNameByCode('SOURCEOFCOUPONPOOL', scope.row.source) }}
          </template>
          </el-table-column>
          <el-table-column
            label="业务类型"
            prop="totalAmount"
            align="center"
            min-width="130"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ getDictionaryNameByCode('BUSINESSTYPE', scope.row.businessType) }}
            </template>
          </el-table-column>
          <el-table-column
            label="冻结状态"
            align="center"
            prop="frozenState"
            min-width="110"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ getDictionaryNameByCode('FROZENSTATE', scope.row.frozenState) }}
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            align="center"
            prop="status"
            min-width="110"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ getDictionaryNameByCode('COUPONPOOLSTATUS', scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column
            label="面值"
            align="center"
            prop="faceValue"
            min-width="110"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="核销方"
            align="center"
            prop="consumer"
            min-width="110"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ getDictionaryNameByCode('COUPONPOOLCONSUMER', scope.row.consumer) }}
            </template>
          </el-table-column>
          <el-table-column
            label="发券方式"
            align="center"
            prop="distributionMethod"
            min-width="110"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ getDictionaryNameByCode('DISTRIBUTIONMETHOD', scope.row.distributionMethod) }}
            </template>
          </el-table-column>
          <el-table-column
            label="服务商"
            align="center"
            prop="serviceProvidersName"
            min-width="110"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="发放有效期"
            align="center"
            min-width="180"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.beginGrantExpiry">
                {{ scope.row.beginGrantExpiry | timestampToChange('date') }} 至 {{ scope.row.endGrantExpiry | timestampToChange('date') }}
              </span>
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column
            label="使用有效期类型"
            align="center"
            min-width="160"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>
                {{ getDictionaryNameByCode('PERIODTYPE', scope.row.periodType) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="使用有效期"
            align="center"
            min-width="180"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.source === '1'">
                {{ scope.row.periodType === '2' ? scope.row.periodDay : scope.row.periodDate}}
              </span>
              <span v-else>
                {{ scope.row.periodDate}}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="投放数量"
            align="center"
            prop="launchQuantity"
            min-width="110"
            :show-overflow-tooltip="true"
          >
          <template slot-scope="scope">
            <span v-if="scope.row.source !== '2'">
              {{ scope.row.launchQuantity === null ? '∞' : scope.row.launchQuantity }}
            </span>
          </template>
          </el-table-column>
          <el-table-column
            label="已发放数量"
            align="center"
            prop="issuedQuantity"
            min-width="110"
            :show-overflow-tooltip="true"
          >
          <template slot-scope="scope">
            <span v-if="scope.row.source !== '2'">
              {{ scope.row.issuedQuantity }}
            </span>
          </template>
          </el-table-column>
          <el-table-column
            label="未发放数量"
            align="center"
            prop="noUsedQuantity"
            min-width="110"
            :show-overflow-tooltip="true"
          >
          <template slot-scope="scope">
            <span v-if="scope.row.source !== '2'">
              {{ scope.row.noUsedQuantity === null ? '∞' : scope.row.noUsedQuantity }}
            </span>
          </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            min-width="160"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ scope.row.createTime | timestampToChange('time') }}
            </template>
          </el-table-column>
          <el-table-column
            label="更新时间"
            align="center"
            min-width="160"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ scope.row.updateTime | timestampToChange('time') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" min-width="180">
            <template slot-scope="scope">
              <el-row type="flex" justify="space-around">
                <el-col v-if="$auth('ticketCenter:ticketPoolManagement:edit')" :span="10">
                  <span v-if="scope.row.status !== '3'" class="colorLink" @click="editCoupon(scope.row)">
                  <i class="el-icon-edit"></i>
                    编辑
                  </span>
                </el-col>
                <el-col v-if="$auth('ticketCenter:ticketPoolManagement:ticketCodeList')" :span="10">
                  <span v-if="scope.row.source === '2' && scope.row.distributionMethod === '1'" class="colorLink" @click="toCouponList(scope.row)">
                    券码列表
                  </span>
                </el-col>
                <el-col v-if="$auth('ticketCenter:ticketPoolManagement:freeze')" :span="10">
                  <!-- v-if="scope.row.frozenState === '1'" -->
                  <span class="colorLink" @click="isFrozen(scope.row)">
                    {{ scope.row.frozenState === '1' ? '冻结' : '解冻' }}
                  </span>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </v-table>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import VNotes from '@/components/Notes/index'
import VTable from '@/components/PageTable/index'
import { common } from '@/mixins/common'
import { getCoupon, saveCoupon, getValidCoupon } from '@/api/coupon'
import { timestampToChange } from '@/filters'

export default {
  name: 'couponMgmt',
  components: {
    VTable,
    VNotes
  },
  mixins: [common],
  computed: {
    ...mapGetters(['lookupItems'])
  },
  data () {
    return {
      loadingText: '加载中...',
      pageLoading: false,
      searchList: {
        createTime: [],
        couponCode: '',
        couponName: '',
        frozenState: '',
        businessType: '',
        serviceProvidersName: '',
        source: '',
        status: '',
        displayStart: '0',
        displayLength: '10'

      },
      isTake: true,
      timeData: {
        createTimeStart: '',
        createTimeEnd: ''
      },
      tableData: [],
      selection: [],
      total: 0,
      pageSize: 10,
      currentPage: 0,
      listLoading: false,
      showContent: false,
      pickerOptions: {
        disabledDate (time) {
          // 如果没有后面的-8.64e7就是不可以选择今天的
          return time.getTime() > Date.now() // - 8.64e7
        }
      }
    }
  },
  created () {
    this.fetchList()
  },
  methods: {
    addCoupon () {
      this.$router.push({ name: 'addCoupon', params: { type: 'add' } })
    },
    toDetail (row) {
      if (!this.$auth('ticketCenter:ticketPoolManagement:detail')) {
        this.$alert('您没有权限')
        return false
      }
      // 跳转详情后的页面与修改时传的 status 的值是一样的， 所以避免详情页多个逻辑判断默认status为3
      this.$router.push({ name: 'couponDetail', params: { id: row.id, status: '3', type: 'detail' } })
    },
    editCoupon (row) {
      if (!this.$auth('ticketCenter:ticketPoolManagement:edit')) {
        this.$alert('您没有权限')
        return false
      }
      this.$router.push({ name: 'couponDetail', params: { id: row.id, status: row.status, type: 'edit' } })
    },
    isFrozen (row) {
      let frozenFlag
      let frozenString
      if (row.frozenState === '1') {
        frozenFlag = true
        frozenString = `是否冻结‘${row.couponName}’券池，冻结后券池将无法发放券码`
      } else {
        frozenFlag = false
        frozenString = `是否解冻‘${row.couponName}’券池`
      }
      this.$alert(frozenString, frozenFlag ? '冻结' : '解冻', {
        showCancelButton: true,
        cancelButtonText: '关闭',
        confirmButtonText: '确定',
        callback: action => {
          if (action === 'confirm') {
            const params = {
              id: row.id,
              frozenState: row.frozenState === '1' ? '2' : '1'
            }
            saveCoupon(params).then(res => {
              if (res) {
                if (Number(res.code) === 1) {
                  this.$alert('状态修改成功')
                  this.fetchList()
                } else {
                  this.$alert('状态修改失败')
                  this.fetchList()
                }
              }
            })
          }
        }
      })
    },
    isAllEqual (array) {
      if (array.length > 0) {
        return !array.some(function (value, index) {
          return value !== array[0]
        })
      } else {
        return true
      }
    },
    compareDate (array) {
      const time = new Date().getTime()
      if (array.length > 0) {
        return array.some(function (value) {
          if (value !== null) {
            return time > value
          } else {
            return false
          }
        })
      } else {
        return true
      }
    },
    takeEffect () {
      const idList = []
      const statusArr = []
      const dateArr = []
      let statusFlag
      let statusString
      let statusTip
      this.selection.forEach(item => {
        idList.push(item.id)
        statusArr.push(item.status)
        dateArr.push(item.endGrantExpiry)
      })
      if (this.isAllEqual(statusArr)) {
        statusArr.forEach(item => {
          if (item === '1') {
            if (this.compareDate(dateArr)) {
              statusTip = '提示'
              statusString = '所选数据中包含超出发放有效期的券池，需重新设定发放有效期。'
              statusFlag = false
            } else {
              statusFlag = true
              statusString = '券池信息生效后无法修改，是否生效'
            }
          } else {
            statusFlag = false
            statusString = '所选券池已生效或已失效，请重新选择'
          }
        })
      } else {
        statusFlag = false
        statusString = '所选券池已生效或已失效，请重新选择'
      }
      const params = {
        ids: idList
      }
      this.$alert(statusString, `${statusTip || '生效'}`, {
        showConfirmButton: statusFlag,
        confirmButtonText: '确定',
        showCancelButton: true,
        cancelButtonText: '关闭',
        callback: action => {
          if (action === 'confirm') {
            this.listLoading = true
            getValidCoupon(params).then(res => {
              if (res) {
                this.listLoading = false
                if (Number(res.code) === 1) {
                  this.$alert('操作成功').then(() => {
                    this.fetchList()
                  })
                }
              }
            })
          }
        }
      })
    },
    // 表格选择变化事件
    handleSelectionChange (val) {
      this.selection = val
      if (this.selection.length !== 0) {
        this.isTake = false
      } else {
        this.isTake = true
      }
    },
    resetForm () {
      this.searchList = {
        createTime: [],
        couponCode: '',
        couponName: '',
        frozenState: '',
        businessType: '',
        serviceProvidersName: '',
        source: '',
        status: '',
        displayStart: '0',
        displayLength: '10'
      }
      this.currentPage = 0
      this.$refs.table.restPage()
      this.fetchList()
    },
    toCouponList (row) {
      this.$router.push({ name: 'couponList', params: { id: row.id } })
    },
    // 获取列表数据
    fetchList (type) {
      if (!this.$auth('ticketCenter:ticketPoolManagement:list')) {
        this.$alert('您没有权限')
        return false
      }
      if (type) {
        this.$refs.table.restPage()
        this.currentPage = 0
      }
      this.listLoading = true
      const params = {
        ...this.searchList,
        createTimeStart: this.searchList.createTime ? new Date(this.searchList.createTime[0] + ' ' + '00:00:00').getTime() : '',
        createTimeEnd: this.searchList.createTime ? new Date(this.searchList.createTime[1] + ' ' + '23:59:59').getTime() : '',
        displayLength: this.pageSize,
        displayStart: this.currentPage
      }
      getCoupon(params).then((res) => {
        this.listLoading = false
        if (res) {
          if (Number(res.code) === 1) {
            const obj = res.obj
            this.tableData = obj.data || []
            if (this.tableData.length !== 0) {
              this.tableData.forEach(item => {
                if (item.beginUsePeriod !== null && item.endUsePeriod !== null) {
                  item.periodDate = timestampToChange(item.beginUsePeriod, 'date') + '至 ' + timestampToChange(item.endUsePeriod, 'date')
                }
              })
            }
            this.total = obj.total
          } else if (Number(res.code) === 0) {
            this.$confirm(res.msg, {
              confirmButtonText: '确定',
              showCancelButton: false
            })
          } else {
            this.$confirm(this.$t(res.code), {
              confirmButtonText: '确定',
              showCancelButton: false
            })
          }
        }
      })
    },
    closeFilter () {
      this.showContent = !this.showContent
    },
    // 每页数据数目改变
    pageSizeChange (size) {
      this.pageSize = size
      this.fetchList()
    },
    // 当前页改变
    currentPageChange (curPage) {
      this.currentPage = curPage - 1
      this.fetchList()
    }
  }
}
</script>
